#include "common_impl.h"

void create_socket_connect(char* token, int* fd){

	struct sockaddr_in sa;
	char *token1, *token2, *ip, *port;
	const char delimiters[] = ":";

	token1 = strtok(token, delimiters);
	token2 = strtok(NULL, delimiters);
	ip = strtok(NULL, delimiters);
	port = strtok(NULL, delimiters);

	memset(&sa, 0, sizeof(sa));
	sa.sin_family      = AF_INET;
	inet_pton(sa.sin_family, ip, &(sa.sin_addr));
	sa.sin_port        = htons(atoi(port));
	if ( (*fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error creating sending socket.\n");
		exit(EXIT_FAILURE);
	}
	if (connect(*fd, (struct sockaddr *) &sa, sizeof(sa)) < 0)
	{
		perror("ERROR on connecting");
		exit(1);
	}
	printf("Connection with server successfull!\n");
}




int creer_socket(int prop, int *port_num) 
{
	/* fonction de creation et d'attachement */

	/* d'une nouvelle socket */
	/* renvoie le numero de descripteur */
	/* et modifie le parametre port_num */


	int fd; // listening socket
	char *endptr;  // for strtol ()

	/* Get port number from the command line , and set to default port if
	     no arguments were supplied
	 */

	*port_num =(int) strtol(PORT, &endptr, 0);

	if ( *endptr ) {
		fprintf(stderr, "ECHOSERV: Invalid port number.\n");
		exit(EXIT_FAILURE);
	}

	/* Create the listening socket */

	if ( (fd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) {
		fprintf(stderr, "ECHOSERV: Error creating listening socket.\n");
		exit(EXIT_FAILURE);
	}

	return fd;
}

int supprime_retour(char* line){

	if (line[strlen(line)-1] == '\n'){
		line[strlen(line)-1] = '\0';
	}
	return 0;
}

/*  Read a line from a socket  */

ssize_t Readline(int sockd, void *vptr, size_t maxlen) {
	ssize_t n, rc;
	char    c, *buffer;

	buffer = vptr;

	for ( n = 1; n < maxlen; n++ ) {

		if ( (rc = read(sockd, &c, 1)) == 1 ) {
			*buffer++ = c;
			if ( c == '\n' )
				break;
		}
		else if ( rc == 0 ) {
			if ( n == 1 )
				return 0;
			else
				break;
		}
		else {
			if ( errno == EINTR )
				continue;
			return -1;
		}
	}

	*buffer = 0;
	return n;
}


/*  Write a line to a socket  */

ssize_t Sendline(int sockd, const void *vptr, size_t n) {
	size_t      nleft;
	ssize_t     nwritten;
	const char *buffer;

	buffer = vptr;
	nleft  = n;

	while ( nleft > 0 ) {
		if ( (nwritten = write(sockd, buffer, nleft)) <= 0 ) {
			if ( errno == EINTR )
				nwritten = 0;
			else
				return -1;
		}
		nleft  -= nwritten;
		buffer += nwritten;
	}



	return n;
}



/* Vous pouvez ecrire ici toutes les fonctions */
/* qui pourraient etre utilisees par le lanceur */
/* et le processus intermediaire. N'oubliez pas */
/* de declarer le prototype de ces nouvelles */
/* fonctions dans common_impl.h */
